package grpc_client

import (
	"context"
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/app/client"
	"longmen/server/pkg/common/app/etcd"
	_const "longmen/server/pkg/common/helper/const"
	pb "longmen/server/pkg/protobuf"

	"google.golang.org/grpc"
	//ws "longmen/server/websocket_grpc/protobuf"
)

type Token struct {
	AppId     string
	AppSecret string
}

// GetRequestMetadata 获取当前请求认证所需的元数据
func (t *Token) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{"app_id": t.AppId, "app_secret": t.AppSecret}, nil
}

// RequireTransportSecurity 是否需要基于 TLS 认证进行安全传输
func (t *Token) RequireTransportSecurity() bool {
	return false
}

func getClientConn(serverName string, token *Token) *grpc.ClientConn {
	conn, err := client.New(
		client.Endpoint(fmt.Sprintf("discovery:///%s", serverName)),
		client.Discovery(etcd.NewEtcdRegister(global2.GetEtcdCli())),
		client.DialOption(grpc.WithPerRPCCredentials(token))).Dial(context.Background())
	if err != nil {
		global2.Log.Fatalf("【%s】服务连接异常:%v", serverName, err)
	}
	return conn
}

func InitGrpc() {
	token := &Token{
		AppId:     global2.Config.GetString("grpc.appid"),
		AppSecret: global2.Config.GetString("grpc.secret"),
	}
	//InitTimGrpc(token)
	InitTaskGrpc(token)
	InitSportsGrpc(token)
	InitNewSportsGrpc(token)
	InitPaymentGrpc(token)
	InitLiveGrpc(token)
	InitHongBaoGrpc(token)
	InitGuessGrpc(token)
	InitExpertGrpc(token)
	InitAccountGrpc(token)
	InitGameGrpc(token)
}

func InitTimGrpc() {
	token := &Token{
		AppId:     global2.Config.GetString("grpc.appid"),
		AppSecret: global2.Config.GetString("grpc.secret"),
	}
	//腾讯IM
	tencentImConn := getClientConn(global2.GetMicroserviceName(_const.GRPC_TENCENT_IM_SERVER_NAME_KEY), token)
	GrpcTencentImClient = pb.NewTencentImServiceClient(tencentImConn)
}

func StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
	clientStream, err := streamer(ctx, desc, cc, method, opts...)
	return clientStream, err
}
